package parserdecoder

import (
	"iptv_server/v3/v2_src/utils/common"
	"iptv_server/v3/v2_src/utils/orderedmap"
)

func withFilter(k *kkv, f common.Filter) *kkv {
	if common.IsEmpty(f) {
		return k
	}
	return withSorterAndFilter(k, nil, f)
}

func withSorter(k *kkv, s common.Sorter) *kkv {
	if common.IsEmpty(s) {
		return k
	}
	return withSorterAndFilter(k, s, nil)
}

func withSorterAndFilter(k *kkv, s common.Sorter, f common.Filter) *kkv {
	if common.IsEmpty(s) && common.IsEmpty(f) {
		return k
	}

	k.ResortKeys(s, f)
	return k
}

func withMapper(kkv1 *kkv, m common.Mapper) *kkv {
	if common.IsEmpty(m) {
		return kkv1
	}

	kkv2 := new_kkv()
	for _, key := range kkv1.Keys() {
		// group name
		v, _ := kkv1.Get(key)

		newKey := m.Get(key)

		v2, ok := kkv2.Get(newKey)
		if !ok {
			v2 = orderedmap.New[[]NameUrl]()
			for _, innerKey := range v.Keys() {
				innerV1, _ := v.Get(innerKey)
				innerV2 := make([]NameUrl, 0)
				innerV2 = append(innerV2, innerV1...)
				v2.Set(innerKey, innerV2)
			}
		} else {
			for _, innerKey := range v.Keys() {
				// channelName
				innerV1, _ := v.Get(innerKey)
				innerV2, ok := v2.Get(innerKey)
				if !ok {
					innerV2 = make([]NameUrl, 0)
				}
				innerV2 = append(innerV2, innerV1...)
				v2.Set(innerKey, innerV2)
			}
		}
		kkv2.Set(newKey, v2)
		// v2.ge
	}
	return kkv2
}
